import { Component } from '@angular/core';

import { NavController, NavParams, ViewController } from 'ionic-angular';
//import { NativeService } from  '../../providers/NativeService';
//import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
//import { UploadPicturePage } from '../uploadPicture/uploadPicture';
import { TempEditMistakesPage } from '../temp-edit-mistake/temp-edit-mistake';
import { QuestionSetPage } from '../question-set/question-set';
import { MistakeService} from '../mistake.service';

import { Http, Headers, RequestOptions } from "@angular/http";


@Component({
  selector: 'page-take-pictures',
  templateUrl: 'take-pictures.html',
 // providers:[NativeService,MistakeService],
 providers:[MistakeService],
})
export class TakePicturesPage {
  selectedItem: any;
  imgPath: string;
  file: File;
  fileList:Array<File>;
  piclist:Array<{path:string,flag:boolean}>;
  public headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              //public nativeService: NativeService,
              public viewCtrl: ViewController,
              private http: Http,
              public mistakeService : MistakeService) {
     this.selectedItem = navParams.get('item');
     this.piclist = []; 
     this.fileList = [];
    //this.piclist.push({path:"../../assets/icon/test1.jpg",flag:true});  
  }

  return(){
    this.viewCtrl.dismiss(this.imgPath);
  }

  preview(event){
    
    var self = this;
    self.file = event;

    var mfile=(<HTMLInputElement>document.getElementById("pickfiles"));
    self.file =mfile.files[0];
    this.fileList.push(self.file);  
    // if (event.files!=null && event.files[0]!=null)  
     {  
     var reader = new FileReader();  
     reader.onload = function(evt){  
     self.imgPath = this.result; 
     self.piclist.push({path:this.result,flag:true});
    } 
     console.log(mfile.files[0]);  
     reader.readAsDataURL(mfile.files[0]);  
    }
      
  }
 
  upload(){
    console.log(this.imgPath);
   // var img = this.imgPath;
    let formData: FormData = new FormData();
   // formData.append('uploadFile', this.file, this.file.name);   
    formData.append('uploadFile',this.imgPath);  //键值对       
    let headers = new Headers({ 
        "Accept": "application/json"
    });
    let options = new RequestOptions({headers:headers});
    this.http.post("http://1bj6037333.imwork.net:16213/error/hello", formData, options)
        .map(res => res.json())
       // .catch(error => Observable.throw(error))
        .subscribe(
            data => console.log('success' + data),
            error => console.log(error)
        )
    //this.http.post('',{img}.map((res: Response)=>res.json()))
  }

  submit(){ 
    if(this.piclist.length <= 0){
      alert("please choose picture");
      this.navCtrl.push(QuestionSetPage,{})
    }else{
      this.piclist.forEach(element=>
         this.mistakeService.submitImg(element.path).then(
         error=>console.log(error)),
         this.navCtrl.push(TempEditMistakesPage, {         
          })
      );   
    }
  }

 /* gotoUpload(){
    this.navCtrl.push(UploadPicturePage, {
    
    });
   }
  */
  removePic(i:number){
    this.piclist[i].flag = false;
   //({path:this.imgPath,flag:false});
   this.piclist.splice(i,1);
  }

  imgChange(event){
    var self = this;
    var reader = new FileReader();
    var prev_img = <HTMLInputElement>document.getElementById("pickfiles");
    var photoFile =  prev_img.files[0];

    reader.onload = function(e){
      let img = new Image();
      var width = 130;
      var height = 165;
      var quality = 0.8;
      var count = 0;
      var canvas = document.createElement("canvas");
      var drawer = canvas.getContext("2d");
      img.src = this.result;
      console.log(img.src.length);
      img.onload = function(){
        canvas.width = width;
        canvas.height = height;
        drawer.drawImage(img,0,0,canvas.width,canvas.height);
        img.src = canvas.toDataURL("image/png",quality);
        console.log(img.src.length);
        if(count < 1){
        self.piclist.push({path:img.src,flag:true});
        count ++;
        }
        if(count < 2){
          count++;
          img.onload = null;
        }
        
      }
      
      
    }


    reader.readAsDataURL(photoFile);

  }


  getbase64(event){  
    var self = this; 
      var prev_img = <HTMLInputElement>document.getElementById("pickfiles");
      function getBase64Image(img) {
      var canvas = document.createElement("canvas");
      var xRate = 100 / img.width;
      var yRate = 100 / img.height;
      canvas.width = 100;
      canvas.height = 100;
      var ctxContent = canvas.getContext("2d");
      //ctx.drawImage(img, 0, 0, img.width, img.height);
      ctxContent.scale(xRate,yRate);
      var ctx = ctxContent.drawImage(img,0,0);
      var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
      var dataURL = canvas.toDataURL("image/"+ext);
      return dataURL;
    }
    //var img = "../../assets/icon/test1.jpg";
  
    var img = prev_img.files[0].name;
    var image = new Image();
    image.src = img;
    image.onload = function(){
    self.imgPath = getBase64Image(image);
    console.log(self.imgPath.length);
    self.piclist.push({path:self.imgPath,flag:true});
    }
  }
    
}
  
 

